function [x_est,gains] = chaos_ekf(y,cfg)
N = cfg.numSamples;
if strcmpi(cfg.type,'tent')
    f_forward = @ekf_forward_tent;
elseif strcmpi(cfg.type,'logistic')
    f_forward = @ekf_forward_logistic;
else
    error('cfg.type');
end

%% 初始化
x_est = zeros(N,1);     % 状态估计
P_est = zeros(N,1);     % 误差协方差
gains= zeros(N,1); % kalman gain

x_est(1) = y(1);
P_est(1) = 1;

%% 扩展卡尔曼滤波主循环
for k = 2:N
    % 预测阶段（基于分段线性化）
    [x_pred,A_k] = f_forward(x_est(k-1),cfg.para);
    P_pred = A_k^2 * P_est(k-1) + cfg.Q; % 协方差预测
    
    % 更新阶段
    H_k = 1;                        % 观测矩阵（直接观测状态）
    G = P_pred * H_k / (H_k*P_pred*H_k + cfg.R);    % 卡尔曼增益
    gains(k) = G;
    x_est(k) = x_pred + G*(y(k) - x_pred);      % 状态更新
    P_est(k) = (1 - G*H_k)*P_pred;             % 协方差更新
end

end

function [x_pred,A_k] = ekf_forward_tent(x_est,alpha)
if x_est <= 0.5
    A_k = 2*alpha;              % 左区间Jacobian矩阵
    x_pred = A_k * x_est;  % 状态预测
else
    A_k = -2*alpha;             % 右区间Jacobian矩阵
    x_pred = A_k * (1 - x_est);
end
end

function [x_pred,A_k] = ekf_forward_logistic(x_est,alpha)
    A_k = alpha-2*alpha*x_est;
    x_pred =alpha*x_est*(1-x_est);
end